package com.zhang.file.service.impl;

import com.zhang.common.exception.myexception.FileUpException;
import com.zhang.file.service.IFileAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public class LocalFileActionImpl implements IFileAction {
    @Value("${myConfig.localFilePrefix}")
    String filePrefix;

    @Override
    public InputStream readFile(String bucket, String filePath) {
        File file = new File(filePrefix + "/" + bucket + "/" + filePath);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    @Override
    public List<String> listBuckets() {
        File file = new File(filePrefix);
//        第一层必须全是目录
        return Arrays.stream(Objects.requireNonNull(file.listFiles())).map(File::getName).collect(Collectors.toList());
    }

    @Override
    public void uploadFile(InputStream inputStream, String bucket, String objectName) {
        String savePath = filePrefix + "/" + bucket + "/" + objectName;
        try {
            OutputStream fileOutputStream = Files.newOutputStream(Paths.get(savePath));
            byte[] buffer = new byte[1024];//缓冲区提高读取效率
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new FileUpException("图片名:"+savePath);
        }
    }
    @Override
    public void deleteFile(String bucket, String filePath) {
        File file = new File(filePrefix + "/" + bucket + "/" + filePath);
        if (file.exists() && file.canWrite()){
            boolean delete = file.delete();
            if (!delete){
                log.error("文件删除失败!");
            }
        }
    }
}
